package com.cn.algorithm01;

/**
 * @author hels
 * @version 1.0
 * @date 2021/9/30 17:11
 */
public class Code02_Sort {

    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[j];
        arr[j] = arr[i];
        arr[i] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {4,9,5,0,2,1,5,7,2,8,1,4,6};

        printArray(arr);
        insertSort2(arr);
        printArray(arr);

        countValue();

    }

    /**
     * 对数器
     */
    public static void countValue() {
        int times = 1000000;
        int[] arr = new int[5];
        for (int i = 0; i < times; i++) {
            int index = (int)(Math.random()*5);
            arr[index]++;
        }

        for(int i = 0; i < 5; i++) {
            System.out.println(arr[i]);
        }
    }

    /**
     * 插入排序二
     */
    public static void insertSort2(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }

        int N = arr.length;
        for (int end = 1; end < N; end++){
            for (int index = end; index > 0 && arr[index-1]>arr[index]; index--) {
                swap(arr, index-1, index);
            }
        }
    }

    /**
     * 插入排序一
     */
    public static void insertSort1(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }

        int N = arr.length;
        for (int end = 1; end < N; end++) {
            int right = end;
            while (right-1 >= 0 && arr[right-1] > arr[right]) {
                swap(arr, right-1, right);
                right--;
            }
        }
    }

    /**
     * 冒泡排序
     */
    public static void bubboSort(int[] arr) {
        if (arr == null & arr.length < 2) {
            return;
        }

        int N = arr.length;
        for (int end = N-1; end >= 0; end--) {
            // 0~end上进行两个数字比较 01 12 23 34 。。end-1 end
            for (int second = 1; second <= end; second++) {
                if (arr[second-1]>arr[second]) {
                    swap(arr, second-1, second);
                }
            }
        }
    }


    /**
     * 选择排序
     */
    public static void selectSort(int[] arr) {
        if(arr == null || arr.length < 2) {
            return;
        }

        int N = arr.length;
        //
        for (int i = 0; i < N; i++) {
             int  minIndex = i;
             for (int j = i+1; j < N; j++) {
                 minIndex = arr[minIndex] > arr[j] ? j : minIndex;
             }
             swap(arr, i, minIndex);
        }
    }

}
